//
//  PushNewsViewController.m
//  Findif
//
//  Created by Mac on 2019/1/23.
//  Copyright © 2019年 Cicel Chen. All rights reserved.
//

#import "PushNewsViewController.h"
#import "AddNewsPictureView.h"
#import "PushNewsTableViewCell.h"
#import "ShopLocalViewController.h"
#import "ChooseLocalViewController.h"
#import "GroupContractsViewController.h"
#import <CoreLocation/CLLocationManager.h>
#import <CoreLocation/CoreLocation.h>

@interface PushNewsViewController ()<UITextViewDelegate,AddNewsPictureViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate>{
    
    UIImagePickerController *_imagePickerController;
    NSMutableArray *_imageArr;//保存添加的图片
}

@property (nonatomic, weak)UITextView * textView;
@property (nonatomic, strong)UIAlertController * alertVC;
@property (nonatomic, strong)AddNewsPictureView * addview;
@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)NSMutableArray * imgArray;
@property (nonatomic, assign)NSInteger count;
@property (nonatomic, weak)UIView * lineView;
@property (nonatomic, copy)NSString * longitude;
@property (nonatomic, copy)NSString * latitude;
@property (nonatomic, copy)NSString * localStr;
//@property (nonatomic, copy)NSString * groupID;

@property (nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation PushNewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = ZRWhiteColor;
    
    self.imgArray = [NSMutableArray array];
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    [self setupNav];
    [self setupUI];
    [self setupAlertVC];
    [self startLocation];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startLocation) name:@"updateUserLocal" object:nil];
}


- (void)setupNav{
    
    self.title = @"发布动态";
    
    UIButton * backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35 * SCREENH6, 15 * SCREENH6)];

    [backButton setTitle:@"取消" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    backButton.titleLabel.font = [UIFont boldSystemFontOfSize:15 * SCREENH6];
    [backButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
    
    UIButton * backButton1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35 * SCREENH6, 15 * SCREENH6)];
    
    //    backButton.frame = CGRectMake(0 , 0 , 65 * SCREENH6, 20 * SCREENH6);
    [backButton1 setTitle:@"发布" forState:UIControlStateNormal];
    backButton1.titleLabel.font = [UIFont boldSystemFontOfSize:15 * SCREENH6];
    [backButton1 setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    
    [backButton1 addTarget:self action:@selector(clickPushButton) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * nextButton = [[UIBarButtonItem alloc] initWithCustomView:backButton1];
    
    self.navigationItem.rightBarButtonItem = nextButton;
    
}


- (void)setupUI{
    // 创建textView
    UITextView * textView =[[UITextView alloc] initWithFrame:CGRectMake(15 * SCREENH6, 10 * SCREENH6, 345 * SCREENH6, 200 * SCREENH6)];
    
    textView.backgroundColor= ZRWhiteColor;
    textView.text = @"记录这一刻，晒给懂你的人~";
    textView.font = [UIFont systemFontOfSize:14 * SCREENH6];
    textView.textColor = ColorWithRGB(0xbebebe);
    textView.delegate = self;
    
    self.textView = textView;
    [self.view addSubview:self.textView];
    
    
    self.addview = [[AddNewsPictureView alloc] initWithFrame:CGRectMake(0, 220 * SCREENH6, kScreenW, 100 * SCREENH6)];
    self.addview.delegate = self;
    
    [self.view addSubview:self.addview];
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xe4e4e4);
    
    self.lineView = lineView;
    
    [self.view addSubview:self.lineView];
    
    
    UITableView * tableView = [[UITableView alloc] init];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ZRWhiteColor;
    tableView.rowHeight = 50 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[PushNewsTableViewCell class] forCellReuseIdentifier:@"PushNewsTableViewCell"];
    
    [self.view addSubview:self.tableView];
    
}

- (void)viewDidLayoutSubviews{
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.top.mas_equalTo(self.addview.mas_bottom).offset(10 * SCREENH6);
        make.height.mas_equalTo(1 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-15 * SCREENH6);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.view);
        make.top.mas_equalTo(self.lineView.mas_bottom);
        make.height.mas_equalTo(100 * SCREENH6);
    }];
}


#pragma mark -UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return 2;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PushNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PushNewsTableViewCell" forIndexPath:indexPath];
    
    if (indexPath.row == 0) {
        
        cell.titleLabel.text = @"所在位置";
        cell.iconImageView.image = [UIImage imageNamed:@"位置"];
    }else if (indexPath.row == 1){
        
        if (self.groupString) {
            
            cell.titleLabel.text = self.groupString;
        }else{
            
            cell.titleLabel.text = @"所在社团";
        }
        
        cell.iconImageView.image = [UIImage imageNamed:@"社团"];
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PushNewsTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    
    HiddenBar;
    
    if (indexPath.row == 0) {
        
        if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
            
            //定位功能可用
            ChooseLocalViewController * localVC = [ChooseLocalViewController new];
            
            [self.navigationController pushViewController:localVC animated:YES];
            
            [localVC returnLocalName:^(NSDictionary *localInfo) {
                
                NSString * name = localInfo[@"name"];
                
                if (localInfo[@"longitude"] && localInfo[@"latitude"]) {
                    
                    self.longitude = localInfo[@"longitude"];
                    self.latitude = localInfo[@"latitude"];
                    self.localStr = localInfo[@"name"];
                }
                
                
                cell.titleLabel.text = name;
            }];
        }else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
            
            //定位不能用
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"亲，请先开启定位服务"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
        
        
    }else{
        
        if ([self.type isEqualToString:@"info"]) {
            
            
        }else{
            
            GroupContractsViewController * groupVC = [GroupContractsViewController new];
            
            [self.navigationController pushViewController:groupVC animated:YES];
            
            [groupVC returnGroupName:^(NSDictionary * _Nonnull localInfo) {
                
                NSString * name = localInfo[@"name"];
                self.groupID = localInfo[@"ID"];
                cell.titleLabel.text = name;
            }];
        }
        
    }
}


- (void)clickPushButton{

    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    if (self.localStr) {
        
        [dict setValue:self.localStr forKey:@"address"];
        [dict setValue:self.longitude forKey:@"longitude"];
        [dict setValue:self.latitude forKey:@"latitude"];
    }
    
    if (self.groupID) {
        
        [dict setValue:self.groupID forKey:@"group_id"];
    }
    
    if ([self.textView.text isEqualToString:@"记录这一刻，晒给懂你的人~"] && self.imgArray.count == 0) {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"内容不能为空"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        
        if ([self.textView.text isEqualToString:@"记录这一刻，晒给懂你的人~"]) {
            
        }else{
            
            [dict setValue:self.textView.text forKey:@"content"];
        }
        
        NSString * merchants_img;
        if (self.imgArray.count > 0) {
            
            merchants_img = [self.imgArray componentsJoinedByString:@","];
            [dict setValue:merchants_img forKey:@"img"];
        }
        
        [[ZRNetworkTool sharedTool] initiateDynamicWithDict:dict.copy WithBlock:^(BOOL success, id responseData) {

            if (success) {
                
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                          [self.navigationController popViewControllerAnimated:YES];
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
    }
    
}

- (void)clickItemButton:(NSInteger )tag{
    
    self.count = tag;
//    self.test = nil;
    [self presentViewController:self.alertVC animated:YES completion:nil];
}

- (void)clickDeleteButton:(NSInteger )tag{
    
    [self.imgArray removeObjectAtIndex:tag - 1];

    if (self.imgArray.count > 2 && self.imgArray.count <= 5) {

        self.addview.height = 200 * SCREENH6;
    }else if(self.imgArray.count > 5 && self.imgArray.count <= 9) {

        self.addview.height = 300 * SCREENH6;
    }else if(self.imgArray.count <= 2) {

        self.addview.height = 100 * SCREENH6;
    }
}

- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}

#pragma mark -实现图片选择器代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage]; //通过key值获取到图片
    //给UIimageView赋值已经选择的相片
    NSData *frontImageData = UIImageJPEGRepresentation(image,0.5);
    NSString *base64Data = [frontImageData base64EncodedStringWithOptions:0];
    NSString * reslut = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",base64Data];
    
    //上传图片到服务器--在这里进行图片上传的网络请求，这里不再介绍
    [[ZRNetworkTool sharedTool] uploadOneImgResultWithImg:reslut WithBlock:^(BOOL success, id responseData) {

        if (success) {
            
            if (self.count > 2 && self.count < 5) {
                
                self.addview.height = 200 * SCREENH6;
                //        self.modeView.y = 440 * SCREENH6;
            }else if(self.count > 5 && self.count <= 9) {
                
                self.addview.height = 300 * SCREENH6;
                //        NSLog(@"self.count < 9=== %f",self.modeView.y);
                //        self.modeView.y = self.modeView.y + 100 * SCREENH6;
                //        self.modeView.y = 540 * SCREENH6;
            }
            
            self.addview.count = self.count;
            self.addview.buttonImage = image;

            NSString * string = [NSString stringWithFormat:@"%@",responseData[@"data"]];

            [self.imgArray addObject:string];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
}

//当用户取消选择的时候，调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}


#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView
{
    
    if(textView.text.length < 1){
        textView.text = @"记录这一刻，晒给懂你的人~";
        textView.textColor = ColorWithRGB(0xbebebe);
    }else{
        
        [textView resignFirstResponder];
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:@"记录这一刻，晒给懂你的人~"]){
        textView.text= @"";
        textView.textColor=[UIColor blackColor];
    }
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.textView resignFirstResponder];
    //    [self.textView endEditing:YES];
}

- (void)backToView{
    
    [self.navigationController popViewControllerAnimated:YES];
}


//开始定位
- (void)startLocation {
    
    if ([CLLocationManager locationServicesEnabled]) {
        //        CLog(@"--------开始定位");
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.delegate = self;
        //控制定位精度,越高耗电量越
        self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        // 总是授权
        [self.locationManager requestWhenInUseAuthorization];
        self.locationManager.distanceFilter = 10.0f;
        //        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager startUpdatingLocation];
    }
}


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}
//定位代理经纬度回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    CLLocation *newLocation = locations[0];
    
    //    self.userLocation = newLocation;
    
    double lat = newLocation.coordinate.latitude;
    double lon = newLocation.coordinate.longitude;
    
    NSString * latStr = [NSString stringWithFormat:@"%f",lat];
    NSString * lonStr = [NSString stringWithFormat:@"%f",lon];
    
    DEF_SET_OBJECT(latStr, @"lat");
    DEF_SET_OBJECT(lonStr, @"lon");
}

@end
